package com.dkh.recommend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.dkh.recommend.dto.BlogUploadDTO;
import com.dkh.recommend.dto.Result;
import com.dkh.recommend.entity.TbBlog;
import com.dkh.recommend.entity.TbBlogImgUrl;
import com.dkh.recommend.entity.TbRelate;
import com.dkh.recommend.mapper.TbBlogImgUrlMapper;
import com.dkh.recommend.mapper.TbBlogMapper;
import com.dkh.recommend.mapper.TbRelateMapper;
import com.dkh.recommend.service.TbBlogImgUrlService;
import com.dkh.recommend.service.TbBlogService;
import com.dkh.recommend.utils.RecScoreUtils;
import com.dkh.recommend.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author DENG
* @description 针对表【tb_blog】的数据库操作Service实现
* @createDate 2023-04-05 01:22:41
*/
@Slf4j
@Service
@Transactional
public class TbBlogServiceImpl extends ServiceImpl<TbBlogMapper, TbBlog> implements TbBlogService {

    @Resource
    private TbBlogImgUrlService blogImgUrlService;

    @Resource
    private TbBlogMapper blogMapper;
    @Resource
    private TbBlogImgUrlMapper blogImgUrlMapper;
    @Resource
    private TbRelateMapper relateMapper;


    /**
     * //    发布音乐故事
     * @param blogUploadDTO
     * @return
     */
    @Override
    @Transactional
    public Result UploadBlog(BlogUploadDTO blogUploadDTO) {
//        获取当前用户id
        Long userId = UserHolder.getUser().getUserId();
        TbBlog tbBlog = BeanUtil.toBean(blogUploadDTO, TbBlog.class);
        tbBlog.setBlogAuthor(userId);
        boolean s1 = this.save(tbBlog);

        if (!s1){
            return Result.fail("发布失败！请重试");
        }
//        保存音乐图片
        List<String> imgUrlList = blogUploadDTO.getImgUrlList();
        if (imgUrlList.size() > 0 && !imgUrlList.isEmpty()){
        List<TbBlogImgUrl> blogImgUrlList = new ArrayList<>();
        imgUrlList.stream().forEach(imgUrl ->{
            TbBlogImgUrl blogImgUrl = new TbBlogImgUrl();
            blogImgUrl.setBlogId(tbBlog.getBlogId());
            blogImgUrl.setImgUrl(imgUrl);
            blogImgUrlList.add(blogImgUrl);
        });
        boolean b = blogImgUrlService.saveBatch(blogImgUrlList);
        if (!b){
            return Result.fail("发布失败！请重试");
        }
        }
        //        分享音乐故事+1分
        TbRelate relate = new TbRelate();
        relate.setMusicId(blogUploadDTO.getMusicId());
        relate.setUserId(userId);
        relate.setIndex(1);
        RecScoreUtils.addScore(relate,relateMapper);

        return Result.ok("发布成功！！");
    }


    /**
     * 根据id删除我的音乐故事
     * @param blogId
     * @return
     */
    @Override
    public Result DeleteMyBlogById(String blogId) {
        Long userId = UserHolder.getUser().getUserId();
        Long blogIdL = Long.valueOf(blogId);
        LambdaQueryWrapper<TbBlog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbBlog::getBlogId,blogIdL).eq(TbBlog::getBlogAuthor,userId);

        //        删除我的音乐故事-1分
        TbBlog blog = this.getOne(wrapper);
        TbRelate relate = new TbRelate();
        relate.setMusicId(blog.getMusicId());
        relate.setUserId(userId);
        relate.setIndex(1);
        RecScoreUtils.decScore(relate,relateMapper);

        boolean b = remove(wrapper);
        if (!b){
            return Result.fail("删除失败");
        }


//        删除关联的图片
        LambdaQueryWrapper<TbBlogImgUrl> imgWrapper = new LambdaQueryWrapper<>();
        imgWrapper.eq(TbBlogImgUrl::getBlogId,blogIdL);
        boolean b1 = blogImgUrlService.remove(imgWrapper);
        if (!b1){
            return Result.fail("删除失败");
        }

        return Result.ok("删除成功！");


    }



    /**
     * //     分页获取blog故事（根据浏览量倒序排序）
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    public Result GetAllBlog(int pageNumber, int pageSize) {

        IPage<TbBlog> blogPage = new Page<>(pageNumber, pageSize);
//       this.page(blogPage);
        LambdaQueryWrapper<TbBlog> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(TbBlog::getPageView);
        this.page(blogPage,wrapper);
        List<TbBlog> records = blogPage.getRecords();
        return Result.ok(blogPage);
    }

    /**
     * 根据blogId 查看blog故事详情(看一次浏览量+1)
     * @param blogId
     * @return
     */
    @Override
    @Transactional
    public Result GetAllInfoById(String blogId) {
        Long blogIdL = Long.valueOf(blogId);
        TbBlog blog = this.getById(blogIdL);

//        blog浏览量 + 1
        blogMapper.addPageView(blogIdL);

        if (blog.toString().isEmpty() || blog.toString() == ""){
            return Result.fail("没有blog详细信息！");
        }

        return Result.ok(blog);
    }

    /**
     *   根据音乐id分页获取blog的音乐故事（浏览量倒序排序）
     * @param musicId
     * @return
     */
    @Override
    public Result GetAllByMusicId(String musicId ,int pageNumber, int pageSize ) {

        Long musicIdL = Long.valueOf(musicId);
//        List<TbBlog> tbBlogList = blogMapper.GetByMusicId(musicIdL);


        IPage<TbBlog> blogPage = new Page<>(pageNumber, pageSize);
//       this.page(blogPage);
        LambdaQueryWrapper<TbBlog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbBlog::getMusicId,musicIdL);
        wrapper.orderByDesc(TbBlog::getPageView);
        this.page(blogPage,wrapper);
//        List<TbBlog> records = blogPage.getRecords();
        return Result.ok(blogPage);

    }

    /**
     *  根据用户id分页获取blog的音乐故事（浏览量倒序排序）
     * @param userId
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    public Result GetAllByUserId(String userId, int pageNumber, int pageSize) {
        Long userIdL = Long.valueOf(userId);

        IPage<TbBlog> blogPage = new Page<>(pageNumber, pageSize);
//       this.page(blogPage);
        LambdaQueryWrapper<TbBlog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbBlog::getBlogAuthor,userIdL);
        wrapper.orderByDesc(TbBlog::getPageView);
        this.page(blogPage,wrapper);
        return Result.ok(blogPage);
    }



    /**
     * 获取blogimgUrlList
     * @param blogId
     * @return
     */
    @Override
    public Result GetBlogImgList(String blogId) {
        Long blogIdL = Long.valueOf(blogId);
        List<String> urlList = blogImgUrlMapper.getImgUrlListByBlogId(blogIdL);
        return Result.ok(urlList);
    }

    /**
     *    根据blog_author获取blog列表
     * @param blogAuthor
     * @return
     */
    @Override
    public Result GetAllByAuthorId(String blogAuthor) {
        Long blogAuthorL = Long.valueOf(blogAuthor);
        List<TbBlog> tbBlogList = blogMapper.GetByblogAuthorId(blogAuthorL);

        return Result.ok(tbBlogList);
    }


}




